// TODO implement group image and group video functionality

import type {
    IDomEditor,
    IEditorConfig,
    SlateDescendant
} from '@wangeditor-next/editor';

import { createEditor, createToolbar } from '@wangeditor-next/editor';


export function setupEditor(
    toolbarSelector: string,
    editorSelector: string,
    readOnly: boolean = false,
    onChange: IEditorConfig['onChange'] = undefined,
    content: SlateDescendant[] = [],
) {
    const editor = createEditor({
        selector: editorSelector,
        config: {
            placeholder: readOnly ? '' : gettext("在这里打字"),
            readOnly: readOnly,
            autoFocus: false,
            onChange: onChange
        },
        mode: 'default', // or 'simple'
        content: content,
    })

    if (!readOnly)
        createToolbar({
            editor,
            selector: toolbarSelector,
            config: {
                excludeKeys: [
                    'group-image',
                    'group-video'
                ]
            },
            mode: 'default'
        })
}


/*
 * Create an wang editor instance directly before the input element,
 * sync content with input element
 * NOTE ELEM shouldn't uses `#` as prefix
 */
export function setupEditorForFormField(
    elem: Element
) {
    const id = elem.id === '' ? 'wang-editor' : `${elem.id}-wang-editor`;
    const readOnly = elem.getAttribute('disabled') == null ? false : true;
    const elemValue = elem.getAttribute('value');
    var initialContent: SlateDescendant[] = [];
    if (elemValue != null)
        initialContent = JSON.parse(elemValue);
    
    // avoid double setup
    if (document.getElementById(id)) return;
    
    elem.insertAdjacentHTML('beforebegin',`
    <div id="${id}" class="tw:border ${ readOnly ? 'by6-input-disabled' : ''}">
       ${readOnly ? '' : '<div class="tw:border-b" data-wang-editor-component="toolbar"></div>'}
        <div data-wang-editor-component='editor'></div>
    </div>
    `);

    setupEditor(
        `#${id}>[data-wang-editor-component='toolbar']`,
        `#${id}>[data-wang-editor-component='editor']`,
        readOnly,
        (editor) => {
            elem.setAttribute('value', JSON.stringify(editor.children));
        },
        initialContent
    )
}

export function setupEditorForFormFields() {
    document.querySelectorAll('[data-wangeditor]').forEach(setupEditorForFormField);
}


